<template>
    <div id="add-edit-register-result">
        <el-form :model="ruleForm" ref="ruleFormRef" size="default" label-width="160px" :rules="rules"> 
            <el-row>
                <el-divider content-position="left">基础信息</el-divider>
                <el-col v-if="isNeedShow" :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                    <el-form-item label="是否受控">
                        <el-switch
                            v-model="isControlled"
                            active-color="#07AAF9"
                            inactive-color="#FF5F33"
                            inline-prompt
                            active-text="受控"
                            inactive-text="不受控"
                            @change="controllChange"
                        />
                    </el-form-item>
                </el-col>
                <div style="width: 100%;" v-if="isControlled === false || !isNeedShow">
                    <el-row>
                        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item label="隐患排查日期">
                                <el-date-picker
                                    v-model="ruleForm.d_CheckDate"
                                    type="date"
                                    value-format="YYYY-MM-DD"
                                    placeholder="请选择开始日期">
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item label="隐患分类" prop="v_HiddenDangerClass">
                                <el-select 
                                    class="m-2" 
                                    placeholder="请选择整改措施" 
                                    v-model="ruleForm.v_HiddenDangerClass" 
                                    @change="hiddenChange"
                                >
                                    <el-option
                                        v-for="item in hiddenOption"
                                        :key="item.id"
                                        :label="item.value"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item label="隐患描述" prop="v_Describe">
                                <el-input v-model="ruleForm.v_Describe" placeholder="请输入隐患描述" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item label="隐患等级">
                                <el-select 
                                    class="m-2" 
                                    placeholder="请选择隐患等级" 
                                    v-model="ruleForm.n_HiddenLevel" 
                                >
                                    <el-option
                                        v-for="item in levelOption"
                                        :key="item.id"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item label="隐患地点">
                                <el-input v-model="ruleForm.v_Place" placeholder="请输入隐患地点" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item label="隐患部位">
                                <el-input v-model="ruleForm.v_Part" placeholder="请输入隐患部位" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item label="隐患排查部门" prop="v_CheckDeptName">
                                <el-cascader 
                                    v-model="ruleForm.l_CheckDeptId"
                                    :options="orgOption" 
                                    :props="orgProps" 
                                    @change="orgChange($event, 1)"
                                    clearable 
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item label="隐患排查人员" prop="v_CheckUserName">
                                <el-select 
                                    v-model="ruleForm.v_CheckUserName" 
                                    filterable 
                                    class="m-2" 
                                    placeholder="选择排查人员" 
                                    @change="useChange($event,1)"
                                    value-key="id"
                                    popper-class="set-select"
                                    :popper-append-to-body="false"
                                >
                                    <el-option
                                        v-for="item in useOptions"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item.id"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-divider content-position="left">整改计划信息</el-divider>
                        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item label="是否为现场整改">
                                <el-switch
                                    v-model="ruleForm.isSceneRectify"
                                    active-color="#07AAF9"
                                    inactive-color="#FF5F33"
                                    inline-prompt
                                    active-text="是"
                                    inactive-text="否"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item label="整改类型">
                                <el-select 
                                    class="m-2" 
                                    placeholder="请选择整改类型" 
                                    v-model="ruleForm.n_Types" 
                                    @change="typesChange"
                                >
                                    <el-option
                                        v-for="item in typesOption"
                                        :key="item.id"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col v-if="ruleForm.n_Types === 1" :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item label="整改期限" prop="d_LimitTime">
                                <el-date-picker
                                    v-model="ruleForm.d_LimitTime"
                                    type="date"
                                    value-format="YYYY-MM-DD"
                                    placeholder="请选择开始日期">
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item label="整改部门" prop="v_RectifyDeptName">
                                <el-cascader 
                                    v-model="ruleForm.l_RectifyDeptId"
                                    :options="orgOption" 
                                    :props="orgProps" 
                                    @change="orgChange($event, 2)"
                                    clearable 
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item label="整改人员" prop="v_RectifyUserName">
                                <el-select 
                                    v-model="ruleForm.v_RectifyUserName" 
                                    filterable 
                                    class="m-2" 
                                    placeholder="选择整改人员" 
                                    @change="useChange($event,2)"
                                    value-key="id"
                                    popper-class="set-select"
                                    :popper-append-to-body="false"
                                >
                                    <el-option
                                        v-for="item in usezgOptions"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item.id"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item label="整改措施" prop="v_Measures">
                                <el-select 
                                    class="m-2" 
                                    placeholder="请选择整改措施" 
                                    v-model="ruleForm.v_Measures" 
                                    @change="typeChange"
                                    multiple
                                    collapse-tags
                                >
                                    <el-option
                                        v-for="item in typeOption"
                                        :key="item.id"
                                        :label="item.value"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-divider content-position="left">隐患图片上传</el-divider>
                        <FileViewTwo 
                            ref="fileRef"
                            isAccept=".jpg,.jpeg,.png"
                            :fileInfo="fileInfo"
                            :componentKey="isAlter"
                        />
                    </el-row>
                </div>
            </el-row>
        </el-form>
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, reactive , toRefs ,toRef, watch , onMounted , nextTick ,watchEffect } from 'vue';
import { ElCol,FormRules, ElForm, ElRow } from 'element-plus';
import FileViewTwo from './file-view-two.vue';
import { SMSIPTaskContentSetControlled } from '/@/api/centerControl/sms';
import { sysUserSelector } from '/@/api/centerControl/pubilc';

/*** 定义接口基础数据类型 */
interface formType {
    ruleForm: ruleFormType,
}
/*** form 表单数据类型 */
type ruleFormType = {
    d_CheckDate: String, // 隐患排查日期
    v_Describe: String, // 隐患描述
    n_HiddenLevel: Number, // 隐患等级
    v_Place: String, // 隐患地点
    v_Part: String, // 隐患部位
    l_CheckUserId: Number, // 隐患排查人员id
    v_CheckUserName: String, // 隐患排查人员名称
    l_CheckDeptId: Number, // 隐患排查部门id
    v_CheckDeptName: String, // 隐患排查部门名称
    n_Type: Number, // 风险分析单元类型
    l_SMSDCListId: Number, // 巡检点记录id
    isCustom: Boolean, // 是否自定义隐患
    v_HiddenDangerClass: String, // 隐患分类
    
    d_LimitTime: String, // 整改期限
    l_RectifyUserId: Number, // 整改人员id
    v_RectifyUserName: String, // 整改人员名称
    l_RectifyDeptId: Number, // 整改部门id
    v_RectifyDeptName: String, // 整改部门名称
    v_Measures: String, // 整改措施集合
    l_HDHiddenId: Number, // 隐患记录Id
    n_Types: Number, // 整改类型
    isSceneRectify: Boolean, // 是否现场整改
}
export default defineComponent( {
    name: 'basics-deploy',
    components: {FileViewTwo},
    props: {
        getInfo: {
            type: Object,
            default: {}
        },
        treeData: {
            type: String,
            default: ''
        },
        typeData: {
            type: String,
            default: ''
        },
        echoInfo: {
            type: Object,
            default: {}
        },
        componentKey: {
            type: Number,
            default: 0
        },
    },
    setup(props,ctx){
        const orgOption = ref();
        const usezgOptions = ref();
        const useOptions = ref();
        const fileInfo = ref('');
        const typeOption = ref();
        const isNeedShow = ref(true);
        const fileRef = ref();
        const ruleFormRef = ref(null);
        const isControlled = ref(); // 是否受控
        const isAlter = ref();
        const hiddenOption = ref();

        /*** 隐患分类改变事件 */
        const hiddenChange = (val: any) => {};

        /*** state 引用接口定义基础数据初始值 */
        const state = reactive < formType > ({
            ruleForm: {} as ruleFormType
        })

        /*** 隐患排查部门改变事件 */
        const orgChange = (val: any, num: number) => {
            let len = val.length - 1;
            if(val && val.length !== 0){
                if(num === 1) {
                    state.ruleForm.l_CheckDeptId = val[len];
                    state.ruleForm.v_CheckDeptName = val[len];
                    state.ruleForm.l_CheckUserId = 0; // 隐患排查人员id
                    state.ruleForm.v_CheckUserName = ''; // 隐患排查人员名称
                }else {
                    state.ruleForm.l_RectifyDeptId = val[len];
                    state.ruleForm.v_RectifyDeptName = val[len];
                    state.ruleForm.l_RectifyUserId = 0; // 整改人员id
                    state.ruleForm.v_RectifyUserName = ''; // 整改人员名称
                }
                useFun(val[len],num);
            }
        }
        
        /*** 隐患排查人员改变事件 */
        const useChange = (val: any, num: number) => {
            if(num === 1) state.ruleForm.l_CheckUserId = val;
            else state.ruleForm.l_RectifyUserId = val;
        }
        /*** 整改人员改变事件 */
        const usezgChange = (val: any) => {
            console.log(val,'val')
        }

        // 获取用户数据
        const useFun = async(id: number, num: number) => {
            let param: any = {};
            param.orgId = id;
            let res:any = await sysUserSelector(param)
            if(res.success){
                if(num === 1) useOptions.value = res.data;
                else usezgOptions.value = res.data;
            }
        }
        
        /*** 基础验证 rules */
        const rules = reactive < FormRules > ({
            /*** 放置验证 */
            // 隐患描述
            v_Describe: [
                { required: true, message: '请输入隐患描述', trigger: 'blur' },
            ],
            // 隐患排查人员
            v_CheckUserName: [
                { required: true, message: '请选择隐患排查人员', trigger: 'change' },
            ],
            // 隐患排查部门
            v_CheckDeptName: [
                { required: true, message: '请选择排查部门', trigger: 'change' },
            ],
            // 整改期限
            d_LimitTime: [
                { required: true, message: '请选择整改期限', trigger: 'change' },
            ],
            // 整改人员
            v_RectifyUserName: [
                { required: true, message: '请选择整改人员', trigger: 'change' },
            ],
            // 整改部门
            v_RectifyDeptName: [
                { required: true, message: '请选择整改部门', trigger: 'change' },
            ],
            // 整改措施
            v_Measures: [
                { required: true, message: '请选择整改措施', trigger: 'change' },
            ],
            // 隐患分类
            v_HiddenDangerClass: [
                { required: true, message: '请选择隐患分类', trigger: 'change' },
            ],
        })

        /*** 整改类型改变事件 */
        const typesChange = (val: any) => {
            console.log(val,'val')
        }

        /*** 整改措施整改措施改变事件 */
        const typeChange = (val: any) => {
            console.log(val,'val')
        }

        /*** 受控/不受控改变事件 */
        const controllChange = (val: any) => {
            controlFun(val);
        }
        // 是否受控函数
        const controlFun = async (bool: boolean) => {
            let param: any = {};
            param.id = props.getInfo.keyId;
            param.isControlled = bool;
            let res: any = await SMSIPTaskContentSetControlled(param);
            if(res.success) return;
        }
        
        watch(() => props.componentKey ,(newVal) => {
            if(newVal){
                isNeedShow.value = false;
                let getData = props.getInfo;
                if(getData.keyId !== 0) {
                    isNeedShow.value = true;
                    if(getData.isControlled === null) {
                        isControlled.value = true; 
                        controlFun(true); 
                    }else if(getData.isControlled === undefined){
                        isNeedShow.value = false;
                    }else{
                        isControlled.value = getData.isControlled;
                    }
                    state.ruleForm.isCustom = false;
                }else {
                    isNeedShow.value = false;
                    state.ruleForm.isCustom = true;
                }

                let setTime = setInterval(() => {
                    if(props.treeData.length !== 0 && props.typeData !== ''){
                        try {
                            orgOption.value = JSON.parse(props.treeData);
                        } catch (error) {
                            console.error('错误信息:', error);
                        }
                        try{
                            typeOption.value = JSON.parse(props.typeData).typeOne;
                        }catch (error) {
                            console.error('错误信息:', error);
                        }
                        try{
                            hiddenOption.value = JSON.parse(props.typeData).typeTwo;
                        }catch (error) {
                            console.error('错误信息:', error);
                        }
                        clearInterval(setTime);
                    }
                },500);
            }
        }, { immediate: true })
        
        /*** 初始化数据声明提前 */
        const initFun = async() => {
            let getData = props.getInfo;
            fileInfo.value = JSON.stringify({sourceId: getData.sourceId});
            state.ruleForm = {
                d_CheckDate: '', // 隐患排查日期
                v_Describe: '', // 隐患描述
                n_HiddenLevel: 3, // 隐患等级
                v_Place: '', // 隐患地点
                v_Part: '', // 隐患部位
                l_CheckUserId: 0, // 隐患排查人员id
                v_CheckUserName: '', // 隐患排查人员名称
                l_CheckDeptId: 0, // 隐患排查部门id
                v_CheckDeptName: '', // 隐患排查部门名称
                n_Type: 0, // 风险分析单元类型
                l_SMSDCListId: 0, // 巡检点记录id
                isCustom: false, // 是否自定义隐患
                v_HiddenDangerClass: '', // 隐患分类

                d_LimitTime: '', // 整改期限
                l_RectifyUserId: 0, // 整改人员id
                v_RectifyUserName: '', // 整改人员名称
                l_RectifyDeptId: 0, // 整改部门id
                v_RectifyDeptName: '', // 整改部门名称
                v_Measures: '', // 整改措施集合
                l_HDHiddenId: 0, // 隐患记录Id
                n_Types: 0, // 整改类型
                isSceneRectify: true, // 是否现场整改
            };
        }
        watchEffect(async() => {
            useOptions.value = [];
            usezgOptions.value = [];
            let echoInfo = props.echoInfo;
            if(Object.keys(echoInfo).length !== 0){
                if(echoInfo.info){
                    let item = JSON.parse(echoInfo.info);
                    state.ruleForm = item;
                    fileInfo.value = JSON.stringify({sourceId: item.l_FileId});
                    await useFun(item.l_CheckDeptId, 1);
                    await useFun(item.l_RectifyDeptId, 2);
                    isAlter.value = props.componentKey;
                }else{
                    await initFun();
                    setTimeout(() => {
                        isAlter.value = props.componentKey;
                    },0);
                }
            }
        })

        watchEffect(() => {
            if(fileRef.value){
                const fileRefInfo = fileRef.value.fileList;
                let getData = props.getInfo;
                let param: any = {};
                param.sourceId = getData.sourceId;
                param.fileVal = fileRefInfo;
                ctx.emit('handelUploadFile',param)
            }
        })

        onMounted(() => {
            nextTick(() => {});
        })
        return{
            ...toRefs(state),
            rules,
            orgOption,
            orgProps: { checkStrictly: true , label: 'title', value: 'id', children: 'children' },
            orgChange,
            useOptions,
            useChange,
            fileInfo,
            levelOption: [
                {id: 3, label: '一般隐患', value: 3},
                {id: 2, label: '严重隐患', value: 2},
                {id: 1, label: '较大隐患', value: 1},
                {id: 0, label: '重大隐患', value: 0},
            ],
            typesChange,
            typesOption: [{id: 0, label: '立即整改' , value: 0},{id: 1, label: '限期整改 ' , value: 1}],
            typeChange,
            typeOption,
            controllChange,
            isNeedShow,
            usezgOptions,
            usezgChange,
            fileRef,
            ruleFormRef,
            isControlled, // 是否受控
            isAlter,
            hiddenChange,
            hiddenOption,
        }
    }
})
</script>
<style scoped lang="scss">
:deep(.is-top){
    margin-right: 20px!important;
}
#file-view{
    width: 100%;
}
:deep(.el-cascader){
    width: 100%;
}
:deep(.el-select){
    width: 100%!important;
}
:deep(.el-input){
    width: 100%;
}
</style>